package com.wens.baselibrary.view.dialog;

import android.app.Activity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;

import org.jetbrains.annotations.NotNull;

public abstract class BaseDialog {
    private final View view;
    private boolean cancelable;

    public BaseDialog(@NotNull Activity activity, int id) {
        ViewGroup viewGroup = (ViewGroup) activity.getWindow().getDecorView();
        view = activity.getLayoutInflater().inflate(id, viewGroup, false);
        viewGroup.addView(view);
        view.setVisibility(View.GONE);
        view.setOnClickListener(v -> {
        });
        initView(view);
    }

    public boolean isCancelable() {
        return cancelable;
    }

    public BaseDialog setCancelable(boolean cancelable) {
        this.cancelable = cancelable;
        return this;
    }

    public boolean isShow() {
        return view.getVisibility() == View.VISIBLE;
    }

    protected abstract void initView(View view);

    public void dismiss() {
        view.setVisibility(View.GONE);
    }

    public void show() {
        view.setVisibility(View.VISIBLE);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (cancelable && isShow()) {
                view.setVisibility(View.GONE);
                return true;
            }
        }
        return false;
    }
}
